<template>
  <div class="leave-management">
    <div class="leave-form">
      <el-card>
        <template #header>
          <div class="card-header">
            <span>申请请假</span>
          </div>
        </template>
        <el-form :model="leaveForm" label-width="100px">
          <el-form-item label="请假类型">
            <el-select v-model="leaveForm.leaveType" placeholder="请选择请假类型" style="width: 100%">
              <el-option label="事假" value="事假"></el-option>
              <el-option label="病假" value="病假"></el-option>
              <el-option label="其他" value="其他"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="请假原因">
            <el-input v-model="leaveForm.leaveReason" type="textarea" :rows="3" placeholder="请输入请假原因"></el-input>
          </el-form-item>
          <el-form-item label="请假时间">
            <el-date-picker
              v-model="leaveForm.dateRange"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              format="YYYY-MM-DD HH:mm"
              value-format="YYYY-MM-DD HH:mm:ss"
              @change="checkLeaveDuration"
            ></el-date-picker>
            <div class="mt-2 leave-duration-hint">
              <el-alert
                type="info"
                :closable="false"
                show-icon
              >
                <template #title>
                  <span class="leave-hint">请假时长说明：最长可线上申请3天请假，超过需线下办理</span>
                </template>
              </el-alert>
            </div>
          </el-form-item>
          <el-form-item label="涉及课程">
            <el-alert
              v-if="longTermLeaveWarning"
              title="请假时长超过3天，需要开具纸质证明，不可通过线上办理"
              type="warning"
              show-icon
              :closable="false"
              class="mb-3"
            ></el-alert>
            <div v-else-if="studentCourses.length === 0" class="text-center">
              <el-empty description="暂无可选课程" :image-size="100"></el-empty>
            </div>
            <div v-else>
              <div class="course-select-header mb-2">
                <span class="select-title">已选课程列表，请选择涉及的课程：</span>
                <div class="select-actions">
                  <el-button type="primary" link @click="selectAllCourses">全选</el-button>
                  <el-button type="info" link @click="deselectAllCourses">取消全选</el-button>
                </div>
              </div>
              <el-checkbox-group v-model="leaveForm.affectedCourses">
                <div class="course-checkbox-container beautify">
                  <el-checkbox 
                    v-for="course in studentCourses" 
                    :key="course.id" 
                    :label="course.id"
                    border
                    class="course-checkbox beautify-checkbox"
                  >
                    <div class="course-item">
                      <div class="course-name">{{ course.name }}</div>
                      <div class="course-info">{{ course.semester }} | {{ course.schedule || '未排课' }}</div>
                    </div>
                  </el-checkbox>
                </div>
              </el-checkbox-group>
            </div>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitLeaveApplication" :disabled="longTermLeaveWarning">提交申请</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>

    <div class="leave-history">
      <el-card class="mt-4">
        <template #header>
          <div class="card-header">
            <span>请假记录</span>
          </div>
        </template>
        <el-table :data="leaveApplications" style="width: 100%">
          <el-table-column prop="leaveType" label="请假类型" width="100" />
          <el-table-column prop="leaveReason" label="请假原因" />
          <el-table-column prop="startDate" label="开始时间" width="180">
            <template #default="scope">
              {{ formatDate(scope.row.startDate) }}
            </template>
          </el-table-column>
          <el-table-column prop="endDate" label="结束时间" width="180">
            <template #default="scope">
              {{ formatDate(scope.row.endDate) }}
            </template>
          </el-table-column>
          <el-table-column prop="affectedCourses" label="涉及课程" width="200">
            <template #default="scope">
              <el-tooltip 
                v-if="scope.row.affectedCourseNames" 
                :content="scope.row.affectedCourseNames" 
                placement="top"
                :show-after="500"
              >
                <span>{{ scope.row.affectedCourseNames }}</span>
              </el-tooltip>
              <span v-else>-</span>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="100">
            <template #default="scope">
              <el-tag :type="getStatusType(scope.row.status)">{{ getStatusText(scope.row.status) }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="拒绝原因" width="150">
            <template #default="scope">
              <span v-if="scope.row.status === 'REJECTED' && scope.row.rejectReason">
                <el-tooltip :content="scope.row.rejectReason" placement="top" :show-after="500">
                  <el-button type="text">查看原因</el-button>
                </el-tooltip>
              </span>
              <span v-else>-</span>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'

export default {
  name: 'LeaveManagement',
  props: {
    studentId: {
      type: Number,
      required: true
    },
    role: {
      type: String,
      default: 'STUDENT'
    }
  },
  setup(props) {
    const leaveForm = ref({
      leaveType: '',
      leaveReason: '',
      dateRange: [],
      affectedCourses: []
    })
    const leaveApplications = ref([])
    const studentCourses = ref([])
    const longTermLeaveWarning = ref(false)
    const submitLoading = ref(false)
    const dialogVisible = ref(false)
    
    // 获取学生已选课程
    const fetchStudentCourses = async () => {
      try {
        // 使用正确的API获取已选课程
        const response = await axios.get(`/api/student/${props.studentId}/courses`);
        studentCourses.value = response.data || [];
        // 为每个课程添加显示名称
        studentCourses.value.forEach(course => {
          course.displayName = `${course.name} (${course.schedule || '未排课'})`;
        });
        console.log('获取到学生课程:', studentCourses.value);
      } catch (error) {
        console.error('获取学生课程失败:', error);
        ElMessage.error('获取学生课程失败，请稍后再试');
      }
    }

    const fetchLeaveApplications = async () => {
      try {
        const response = await axios.get(`/api/users/me/leave-applications?studentId=${props.studentId}`)
        leaveApplications.value = response.data
        
        // 获取涉及课程的名称
        for (const app of leaveApplications.value) {
          if (app.affectedCourses) {
            const courseIds = app.affectedCourses.split(',')
            const courseNames = []
            
            for (const id of courseIds) {
              const course = studentCourses.value.find(c => c.id === id)
              if (course) {
                courseNames.push(course.name)
              }
            }
            
            app.affectedCourseNames = courseNames.join(', ')
          } else {
            app.affectedCourseNames = ''
          }
        }
      } catch (error) {
        console.error('获取请假记录失败:', error)
        ElMessage.error('获取请假记录失败')
      }
    }
    
    // 检查请假时长
    const checkLeaveDuration = async () => {
      if (!leaveForm.value.dateRange || leaveForm.value.dateRange.length !== 2) {
        return
      }
      
      try {
        // 前端自行计算请假时长（天数）
        const startDate = new Date(leaveForm.value.dateRange[0])
        const endDate = new Date(leaveForm.value.dateRange[1])
        
        console.log('检查请假时长:', startDate, endDate)
        
        // 计算天数差异 (毫秒转天数)
        const diffTime = Math.abs(endDate - startDate)
        const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))
        
        console.log('计算的请假天数:', diffDays)
        
        // 如果超过3天，直接在前端显示警告
        if (diffDays > 3) {
          longTermLeaveWarning.value = true
          ElMessage.warning('请假时长超过3天，需要开具纸质证明，不可通过线上办理')
          return
        } else {
          // 重要：如果不超过3天，确保清除警告状态
          longTermLeaveWarning.value = false
        }
        
        // 转换为ISO字符串格式发送到后端进行二次验证
        const startDateISO = startDate.toISOString()
        const endDateISO = endDate.toISOString()
        
        try {
          const response = await axios.get('/api/leave-application/check-duration', {
            params: { startDate: startDateISO, endDate: endDateISO }
          })
          
          console.log('后端验证请假时长响应:', response.data)
          
          longTermLeaveWarning.value = response.data.isLongTerm
          if (response.data.isLongTerm) {
            ElMessage.warning(response.data.message || '请假时长超过3天，需要开具纸质证明，不可通过线上办理')
          }
        } catch (error) {
          console.error('后端验证请假时长失败:', error)
          // 如果后端验证失败，使用前端计算结果
          longTermLeaveWarning.value = diffDays > 3
        }
      } catch (error) {
        console.error('检查请假时长失败:', error)
        ElMessage.error('检查请假时长失败，请稍后再试')
      }
    }
    
    // 提交请假申请
    const submitLeaveApplication = async () => {
      if (!validateLeaveForm()) {
        return
      }
      
      // 再次检查请假时长
      const startDate = new Date(leaveForm.value.dateRange[0])
      const endDate = new Date(leaveForm.value.dateRange[1])
      
      // 计算天数差异 (毫秒转天数)
      const diffTime = Math.abs(endDate - startDate)
      const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))
      
      // 如果超过3天，拒绝提交
      if (diffDays > 3) {
        longTermLeaveWarning.value = true
        ElMessage.error('请假时长超过3天，需要开具纸质证明，不可通过线上办理')
        return
      } else {
        // 清除可能存在的警告状态
        longTermLeaveWarning.value = false
      }
      
      submitLoading.value = true
      try {
        // 转换日期格式
        const application = {
          ...leaveForm.value,
          studentId: props.studentId,
          startDate: startDate.toISOString(),
          endDate: endDate.toISOString(),
          affectedCourses: leaveForm.value.affectedCourses.join(',')
        }
        
        // 移除不需要的字段
        delete application.dateRange
        
        console.log('提交请假申请:', application)
        
        const response = await axios.post('/api/leave-application', application)
        
        if (response.data.success) {
          ElMessage.success('请假申请提交成功')
          resetForm()
          fetchLeaveApplications()
          dialogVisible.value = false
        } else {
          ElMessage.error(response.data.message || '请假申请提交失败')
        }
      } catch (error) {
        console.error('提交请假申请失败:', error)
        ElMessage.error('提交请假申请失败，错误：' + (error.response?.data?.message || error.message))
      } finally {
        submitLoading.value = false
      }
    }

    const validateLeaveForm = () => {
      if (!leaveForm.value.leaveType) {
        ElMessage.warning('请选择请假类型')
        return false
      }
      if (!leaveForm.value.leaveReason) {
        ElMessage.warning('请填写请假原因')
        return false
      }
      if (!leaveForm.value.dateRange || leaveForm.value.dateRange.length !== 2) {
        ElMessage.warning('请选择请假时间')
        return false
      }
      
      // 再次计算请假天数，确保状态正确
      const startDate = new Date(leaveForm.value.dateRange[0])
      const endDate = new Date(leaveForm.value.dateRange[1])
      const diffTime = Math.abs(endDate - startDate)
      const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))
      
      // 更新警告状态
      longTermLeaveWarning.value = diffDays > 3
      
      if (longTermLeaveWarning.value) {
        ElMessage.warning('请假时长超过3天，需要开具纸质证明，不可通过线上办理')
        return false
      }
      
      if (leaveForm.value.affectedCourses.length === 0) {
        ElMessage.warning('请选择涉及的课程')
        return false
      }
      return true
    }

    const resetForm = () => {
      leaveForm.value.leaveType = ''
      leaveForm.value.leaveReason = ''
      leaveForm.value.dateRange = []
      leaveForm.value.affectedCourses = []
      longTermLeaveWarning.value = false
    }

    const getStatusType = (status) => {
      const statusMap = {
        'PENDING': 'warning',
        'APPROVED': 'success',
        'REJECTED': 'danger'
      }
      return statusMap[status] || 'info'
    }

    const getStatusText = (status) => {
      const statusMap = {
        'PENDING': '待审批',
        'APPROVED': '已批准',
        'REJECTED': '已拒绝'
      }
      return statusMap[status] || '未知'
    }

    // 选择课程
    /* eslint-disable no-unused-vars */
    const selectCourse = (courseId) => {
      if (!leaveForm.value.affectedCourses.includes(courseId)) {
        leaveForm.value.affectedCourses.push(courseId)
      }
    }
    
    // 取消选择课程
    const deselectCourse = (courseId) => {
      const index = leaveForm.value.affectedCourses.indexOf(courseId)
      if (index !== -1) {
        leaveForm.value.affectedCourses.splice(index, 1)
      }
    }
    /* eslint-enable no-unused-vars */
    
    // 全选课程
    const selectAllCourses = () => {
      leaveForm.value.affectedCourses = studentCourses.value.map(course => course.id)
    }
    
    // 取消全选课程
    const deselectAllCourses = () => {
      leaveForm.value.affectedCourses = []
    }

    const formatDate = (isoDate) => {
      if (!isoDate) return '';
      const d = new Date(isoDate);
      return `${d.getFullYear()}/${d.getMonth()+1}/${d.getDate()} ${d.getHours().toString().padStart(2,'0')}:${d.getMinutes().toString().padStart(2,'0')}`;
    }

    let timer = null
    onMounted(() => {
      fetchStudentCourses()
      fetchLeaveApplications()
      // 定时轮询刷新
      timer = setInterval(() => {
        fetchLeaveApplications()
      }, 5000)
    })
    onUnmounted(() => {
      if (timer) clearInterval(timer)
    })

    return {
      leaveForm,
      leaveApplications,
      studentCourses,
      longTermLeaveWarning,
      submitLeaveApplication,
      checkLeaveDuration,
      selectAllCourses,
      deselectAllCourses,
      getStatusType,
      getStatusText,
      submitLoading,
      dialogVisible,
      resetForm,
      formatDate
    }
  }
}
</script>

<style scoped>
.leave-management {
  margin-top: 20px;
}

.leave-history {
  margin-top: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.mb-2 {
  margin-bottom: 0.5rem;
}

.mb-3 {
  margin-bottom: 0.75rem;
}

.mt-4 {
  margin-top: 1rem;
}

.text-center {
  text-align: center;
}

.course-select-header {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  margin-bottom: 8px;
}

.select-title {
  font-weight: 500;
  color: #333;
  margin-right: 16px;
}

.select-actions {
  display: flex;
  gap: 8px;
}

.course-checkbox-container.beautify {
  display: flex;
  flex-wrap: wrap;
  gap: 20px 24px;
  margin-top: 10px;
  padding: 8px 0 8px 0;
}

.course-checkbox.beautify-checkbox {
  min-width: 220px;
  max-width: 260px;
  background: #f8fafd;
  border-radius: 8px;
  box-shadow: 0 1px 4px rgba(0,0,0,0.03);
  margin-bottom: 8px;
  transition: box-shadow 0.2s;
}

.course-checkbox.beautify-checkbox.is-checked {
  background: #e6f7ff;
  border-color: #409eff;
  box-shadow: 0 2px 8px rgba(64,158,255,0.08);
}

.course-item {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.course-name {
  font-weight: bold;
  color: #409eff;
  font-size: 1.08em;
}

.course-info {
  font-size: 0.92em;
  color: #606266;
  margin-top: 2px;
}

.el-checkbox.is-bordered + .el-checkbox.is-bordered {
  margin-left: 0;
}

.leave-duration-hint {
  margin-top: 8px;
}

.leave-hint {
  font-size: 13px;
  color: #409eff;
  font-weight: normal;
}
</style>